import axios, {type AxiosResponse} from "axios";
import {getServerToken, removeServerToken, setServerToken} from "@/utils/token.ts";
import router from "@/router";
import {ElMessage} from "element-plus";

axios.defaults.headers["Content-Type"] = "application/json;charset=UTF-8";

const serverRequest = axios.create({
    baseURL: "/server-request",
    timeout: 5000,
})

// 请求拦截器
serverRequest.interceptors.request.use(
    function (config) {
        if (getServerToken()) {
            config.headers["Authorization"] = "Bearer " + getServerToken();
        }
        return config;
    },
    function (error) {
        console.log(error);
        return Promise.reject(error);
    }
)

// 响应拦截器
serverRequest.interceptors.response.use(
    async function (result: AxiosResponse) {
        const code = result.data.code;
        const message = result.data.message
        const authorizationHeader = result.headers['authorization'];
        if (code === 4001) {
            // 登录过期或未登录
            removeServerToken();
            ElMessage({
                message: message,
                type: 'warning',
            })
            // 必须加await，不然页面可能不会跳转
            await router.push("/server/login");
            return Promise.reject(new Error(message));
        } else if (code !== 2000) {
            // 请求操作失败
            // ElMessage.error(message)
            return Promise.reject(message);
        } else {
            console.log(authorizationHeader)
            if (authorizationHeader && authorizationHeader.startsWith('Bearer ')) {
                // 登录成功，更新token
                const token = authorizationHeader.replace('Bearer ', '');
                setServerToken(token);
            }
            return Promise.resolve(result.data.data);
        }
    },
    function (error) {
        return Promise.reject(error);
    }
)

export default serverRequest;